package com.fc.commons;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipHelper {
	private static int zipLevel=5;
	private static int DEFUALT_BUFFER_SIZE=2048;
	
	/**
	 * 解压
	 * @param source
	 * @return
	 */
	public static byte[] zip(byte[] source){
		return zip(source,zipLevel);
	}
	/**
	 * 压缩
	 * @param source
	 * @param level
	 * @return
	 */
	public static  byte[] zip(byte[] source,int level){
		ByteArrayInputStream bais = new ByteArrayInputStream(source);  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        byte[] output = null;
        // 压缩  
        try {
			compress(bais, baos);
  
			output = baos.toByteArray();  
  
        
        baos.flush();  
        baos.close();  
  
        bais.close();  
        } catch (Exception e) {
			e.printStackTrace();
		}  
        return output; 
	}
	
	public static void compress(InputStream is, OutputStream os)  
            throws Exception {  
  
        GZIPOutputStream gos = new GZIPOutputStream(os);  
  
        int count;  
        byte data[] = new byte[DEFUALT_BUFFER_SIZE];  
        while ((count = is.read(data, 0, DEFUALT_BUFFER_SIZE)) != -1) {  
            gos.write(data, 0, count);  
        }  
  
        gos.finish();  
  
        gos.flush();  
        gos.close();  
    }  
	
	
	public static byte[] unZip(byte[] source) {
		if (source == null || source.length == 0) {
			return source;
		}
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ByteArrayInputStream in = new ByteArrayInputStream(source);
			GZIPInputStream gunzip = new GZIPInputStream(in);
			byte[] buffer = new byte[256];
			int n;
			while ((n = gunzip.read(buffer)) >= 0) {
				out.write(buffer, 0, n);
			}
			return out.toByteArray();
		} catch (Exception ex) {
			ex.printStackTrace();
			return source;
		}
	}
}
